package com.roc.steelend.Intercept;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.roc.steelend.util.JWTUtil;
import org.springframework.web.servlet.HandlerAdapter;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

public class JWTIntercept  implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        try {
            DecodedJWT token1 = JWTUtil.getToken(token);
            return  true;
        } catch (Exception e) {
            e.printStackTrace();
            HashMap<String, Object> objectObjectHashMap = new HashMap<>();
            objectObjectHashMap.put("msg","token已过期或无效");
            objectObjectHashMap.put("tokenCode",400);
            String s = new ObjectMapper().writeValueAsString(objectObjectHashMap);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().println(s);

            return false;
        }



    }
}
